import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserService } from '../user/user.service';

@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService
  ) {}

  /**
   * 登录颁发jwt, 返回token
   */
  async signIn(email: string, psw: string) {
    const user = await this.userService.getUserByEmail(email);
    if (!user) {
      throw new Error('账号不存在');
    }
    if (user?.psw !== psw) {
      throw new UnauthorizedException("密码错误");
    }
    return this.jwtService.sign({ 
      userId: user.id,
      userEmail: user.email
    });
  }

  /**
   * 验证token
   * $(AuthService).verifyToken('')
   */
  async verifyToken(token: string) {
    return this.jwtService.verifyAsync(token).then(payload => {
      console.log('认证成功', payload);
      return !!payload;
    }).catch(error => {
      console.warn('认证失败', error);
      return false;
    })
  }
}
